Test Methods in TestNG
Test methods are the methods in a TestNG test class that contain the actual test scenarios to be executed by the TestNG framework. A test method is normally identified using the @Test annotation. In Selenium automation, test methods contain actions such as opening a web page, locating elements, entering data, clicking buttons, validating results, and performing assertions.
Test methods are one of the most important parts of a Selenium + TestNG automation framework because they represent individual automated test cases. TestNG also provides attributes that allow test methods to be grouped, prioritized, parameterized, repeated, skipped, dependent on other methods, or given execution limits.
Course Resource: Selenium Training | Register for Course Demo
1. What are Test Methods?
A test method is a Java method that TestNG recognizes as an automated test when it is annotated with @Test.
The test method contains the actions and validations required to verify a particular application behavior.
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void verifyValidLogin() {
System.out.println("Valid login test executed");
}
}
In this example, verifyValidLogin() is a TestNG test method because it is marked with @Test.
2. Why are Test Methods Important?
Test methods allow large application test scenarios to be divided into smaller, understandable, and independently executable test cases.
- Represent individual test scenarios.
- Execute Selenium automation steps.
- Perform application validations.
- Use TestNG assertions.
- Support test grouping.
- Support test dependencies.
- Support data-driven testing.
- Support repeated execution.
- Support execution priorities.
- Can be enabled or disabled.
- Can define expected exceptions.
- Can define execution timeouts.
- Can integrate with reporting frameworks.
3. Basic Structure of a Test Method
import org.testng.annotations.Test;
public class SampleTest {
@Test
public void testMethod() {
// Test setup if required
// Perform test actions
// Validate expected result
// Test cleanup if required
}
}
A well-designed test method normally follows a logical sequence:
Test Method
|
v
Arrange
|
v
Act
|
v
Validate
|
v
Result
|
v
Cleanup
4. @Test Annotation
The @Test annotation tells TestNG that a method should be treated as a test method.
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void loginTest() {
System.out.println("Login test");
}
}
When TestNG executes this class, it detects the method annotated with @Test and schedules it for test execution.
5. Simple Test Method Example
import org.testng.Assert;
import org.testng.annotations.Test;
public class CalculatorTest {
@Test
public void additionTest() {
int a = 10;
int b = 20;
int result = a + b;
Assert.assertEquals(result, 30);
}
}
This test method calculates the sum of two numbers and validates the result using TestNG's Assert.assertEquals().
6. Selenium Test Method
In Selenium automation, a test method generally interacts with a web application and validates the expected behavior.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class GoogleTest {
@Test
public void verifyGoogleTitle() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
String title = driver.getTitle();
Assert.assertTrue(title.contains("Google"));
driver.quit();
}
}
The test method performs browser initialization, navigation, validation, and cleanup. In a larger framework, WebDriver setup and cleanup are usually moved into configuration methods such as @BeforeMethod and @AfterMethod.
7. Test Method Execution Flow
TestNG
|
v
Identify @Test Methods
|
v
Execute Configuration
|
v
@BeforeMethod
|
v
@Test Method
|
v
Assertion / Validation
|
v
@AfterMethod
|
v
Test Result
|
+-- PASS
|
+-- FAIL
|
+-- SKIP
8. Multiple Test Methods in One Class
A single TestNG class can contain multiple test methods.
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void validLoginTest() {
System.out.println("Valid Login");
}
@Test
public void invalidLoginTest() {
System.out.println("Invalid Login");
}
@Test
public void forgotPasswordTest() {
System.out.println("Forgot Password");
}
}
Each method is treated as a separate test method by TestNG.
9. Independent Test Methods
Test methods should preferably be independent whenever possible. An independent test can execute without depending on the result or state created by another test.
@Test
public void verifyLoginPage() {
System.out.println("Login page test");
}
@Test
public void verifyRegistrationPage() {
System.out.println("Registration page test");
}
@Test
public void verifyForgotPasswordPage() {
System.out.println("Forgot password test");
}
Independent tests are generally easier to debug, rerun, maintain, and execute in parallel.
10. Test Method Naming
Test method names should clearly describe what the test verifies.
Good Names
@Test
public void verifyValidLogin() {
}
@Test
public void verifyInvalidLoginErrorMessage() {
}
@Test
public void verifyProductSearchResults() {
}
@Test
public void verifyUserCanLogout() {
}
Poor Names
@Test
public void test1() {
}
@Test
public void abc() {
}
@Test
public void testMethod() {
}
Meaningful names make automation reports and debugging easier.
11. Test Method with Assertions
Test methods normally contain one or more validations. TestNG provides assertion methods to compare actual and expected behavior.
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void verifyLoginPageTitle() {
String actualTitle = "Login Page";
String expectedTitle = "Login Page";
Assert.assertEquals(actualTitle, expectedTitle);
}
}
Annotations control test execution, while assertions validate whether the application produced the expected result.
12. Common TestNG Assertions Used in Test Methods
| Assertion | Purpose |
| assertEquals() | Checks whether two values are equal |
| assertNotEquals() | Checks whether two values are different |
| assertTrue() | Checks whether a condition is true |
| assertFalse() | Checks whether a condition is false |
| assertNull() | Checks whether a value is null |
| assertNotNull() | Checks whether a value is not null |
| assertSame() | Checks whether two references refer to the same object |
| assertNotSame() | Checks whether two references are different objects |
13. Test Methods with Selenium WebElements
A Selenium test method can locate web elements and perform actions such as click, type, select, submit, and validation.
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test
public void verifyLogin() {
driver.findElement(By.id("username"))
.sendKeys("admin");
driver.findElement(By.id("password"))
.sendKeys("admin123");
driver.findElement(By.id("login"))
.click();
Assert.assertTrue(
driver.getCurrentUrl().contains("dashboard")
);
}
}
14. Test Methods with @BeforeMethod and @AfterMethod
For Selenium projects, browser initialization and cleanup can be separated from test logic.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
Test Class
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test
public void validLoginTest() {
driver.get("https://example.com/login");
Assert.assertTrue(
driver.getTitle().contains("Login")
);
}
@Test
public void invalidLoginTest() {
driver.get("https://example.com/login");
Assert.assertTrue(
driver.getCurrentUrl().contains("login")
);
}
}
15. Test Method Attributes
TestNG provides many attributes for controlling how test methods behave.
| Attribute | Purpose |
| priority | Defines relative execution priority |
| enabled | Enables or disables a test |
| groups | Assigns a test to groups |
| description | Provides test description |
| dependsOnMethods | Creates dependency on specific methods |
| dependsOnGroups | Creates dependency on groups |
| dataProvider | Connects test to a DataProvider |
| dataProviderClass | Specifies external DataProvider class |
| expectedExceptions | Defines expected exception types |
| timeOut | Defines maximum test execution time |
| invocationCount | Runs the test multiple times |
| invocationTimeOut | Limits time for repeated invocations |
| threadPoolSize | Controls threads for repeated invocations when applicable |
| alwaysRun | Controls execution behavior in dependency scenarios |
16. Test Method with Priority
The priority attribute can be used to define relative execution order.
@Test(priority = 1)
public void loginTest() {
System.out.println("Login");
}
@Test(priority = 2)
public void searchTest() {
System.out.println("Search");
}
@Test(priority = 3)
public void logoutTest() {
System.out.println("Logout");
}
Lower priority values are generally scheduled before higher priority values. Priority should not be used as a substitute for proper test independence or dependencies.
17. Test Method with Description
The description attribute provides information about the purpose of a test.
@Test(description = "Verify successful user login")
public void verifyValidLogin() {
System.out.println("Valid login test");
}
Descriptions can improve the readability of test execution reports.
18. Enabled and Disabled Test Methods
The enabled attribute determines whether a test method is enabled for execution.
@Test(enabled = true)
public void activeTest() {
System.out.println("Active test");
}
@Test(enabled = false)
public void disabledTest() {
System.out.println("Disabled test");
}
A disabled test is excluded from normal execution. Disabled tests should be reviewed periodically so that obsolete test cases do not remain unnecessarily excluded.
19. Test Methods with Groups
TestNG groups allow test methods to be categorized according to their purpose or execution requirement.
@Test(groups = "smoke")
public void verifyLogin() {
System.out.println("Smoke test");
}
@Test(groups = "regression")
public void verifyCheckout() {
System.out.println("Regression test");
}
@Test(groups = {"smoke", "regression"})
public void verifySearch() {
System.out.println("Smoke and regression test");
}
Common Test Groups
- Smoke
- Sanity
- Regression
- Functional
- Integration
- End-to-End
- Critical
- UI
20. Test Methods with dependsOnMethods
The dependsOnMethods attribute defines a dependency between test methods.
@Test
public void loginTest() {
System.out.println("Login successful");
}
@Test(dependsOnMethods = "loginTest")
public void checkoutTest() {
System.out.println("Checkout test");
}
Here, the checkout test depends on the login test. If the required dependency fails, TestNG can skip the dependent test according to its dependency handling.
Dependencies should be used only when there is a genuine relationship between test scenarios.
21. Test Methods with dependsOnGroups
The dependsOnGroups attribute allows a test method to depend on one or more groups.
@Test(groups = "login")
public void loginTest() {
System.out.println("Login");
}
@Test(groups = "login")
public void sessionValidationTest() {
System.out.println("Session validation");
}
@Test(dependsOnGroups = "login")
public void checkoutTest() {
System.out.println("Checkout");
}
22. Test Methods with DataProvider
TestNG DataProvider allows a single test method to execute with multiple sets of input data.
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginDataTest {
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"admin", "admin123"},
{"user1", "password1"},
{"user2", "password2"}
};
}
@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}
The test method runs once for each row of data returned by the DataProvider.
23. Data-Driven Selenium Test Method
import org.openqa.selenium.By;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@DataProvider(name = "users")
public Object[][] users() {
return new Object[][] {
{"admin", "admin123"},
{"tester", "test123"},
{"user", "user123"}
};
}
@Test(dataProvider = "users")
public void verifyLogin(String username, String password) {
driver.get("https://example.com/login");
driver.findElement(By.id("username"))
.sendKeys(username);
driver.findElement(By.id("password"))
.sendKeys(password);
driver.findElement(By.id("login"))
.click();
}
}
24. Test Method with Expected Exception
The expectedExceptions attribute is useful when an exception is the expected result of a test.
@Test(expectedExceptions = ArithmeticException.class)
public void verifyDivisionByZero() {
int result = 10 / 0;
}
If the expected exception occurs, TestNG evaluates the test according to the declared expectation.
25. Test Method with Timeout
The timeOut attribute specifies the maximum amount of time allowed for a test method.
@Test(timeOut = 5000)
public void verifyPageLoad() {
System.out.println("Page validation test");
}
The value is specified in milliseconds. Selenium synchronization should normally be handled using appropriate waits rather than relying on unnecessarily large test method timeouts.
26. Test Method with invocationCount
The invocationCount attribute allows a test method to execute multiple times.
@Test(invocationCount = 5)
public void repeatedTest() {
System.out.println("Test executed");
}
The same test method is invoked five times.
Use Case
- Repeated validation.
- Basic stability checks.
- Testing repeated operations.
- Checking behavior under repeated execution.
27. Test Method with threadPoolSize
threadPoolSize can be used with repeated test invocations when parallel invocation is required.
@Test(
invocationCount = 6,
threadPoolSize = 3
)
public void parallelTest() {
System.out.println("Parallel invocation");
}
When using parallel execution, test data, WebDriver instances, files, and other shared resources must be designed for proper isolation.
28. Test Method with alwaysRun
The alwaysRun attribute can affect execution behavior when dependencies are involved.
@Test(alwaysRun = true)
public void cleanupValidation() {
System.out.println("Validation test");
}
For configuration methods, alwaysRun = true is especially useful for important cleanup operations such as closing WebDriver sessions.
@AfterMethod(alwaysRun = true)
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
29. Test Methods and TestNG Assertions
Test methods perform actions and assertions validate results. These are related but different responsibilities.
@Test
public void verifyLogin() {
// Action
driver.findElement(By.id("login")).click();
// Validation
Assert.assertTrue(
driver.getCurrentUrl().contains("dashboard")
);
}
Test Method
|
+-- Perform Action
|
+-- Capture Actual Result
|
+-- Compare Expected Result
|
+-- Assertion
|
+-- PASS / FAIL
30. Hard Assertions in Test Methods
Hard assertions immediately stop the current test method when an assertion fails.
@Test
public void verifyPage() {
Assert.assertEquals(
driver.getTitle(),
"Dashboard"
);
System.out.println("This line runs only if assertion passes");
}
31. Soft Assertions in Test Methods
Soft assertions allow multiple validations to be collected before the final result is evaluated.
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class DashboardTest {
@Test
public void verifyDashboard() {
SoftAssert softAssert = new SoftAssert();
softAssert.assertTrue(true);
softAssert.assertEquals("Dashboard", "Dashboard");
softAssert.assertTrue(true);
softAssert.assertAll();
}
}
assertAll() is important because it reports the collected soft assertion failures at the end of the validation sequence.
32. Test Method Lifecycle with Configuration Methods
@BeforeSuite
|
v
@BeforeTest
|
v
@BeforeClass
|
v
@BeforeMethod
|
v
@Test Method
|
+-- Selenium Actions
+-- Assertions
|
v
@AfterMethod
|
v
@AfterClass
|
v
@AfterTest
|
v
@AfterSuite
This diagram represents a simplified lifecycle. The exact execution sequence can depend on the suite, classes, groups, inheritance, dependencies, and TestNG configuration.
33. Test Methods with Multiple Tests
public class EcommerceTest extends BaseTest {
@Test
public void verifyLogin() {
System.out.println("Login test");
}
@Test
public void verifyProductSearch() {
System.out.println("Product search test");
}
@Test
public void verifyAddToCart() {
System.out.println("Add to cart test");
}
@Test
public void verifyCheckout() {
System.out.println("Checkout test");
}
@Test
public void verifyLogout() {
System.out.println("Logout test");
}
}
Each method represents a separate test scenario.
34. Test Method Organization
Large automation projects should organize test methods logically instead of placing unrelated tests in one class.
src/test/java
|
+-- tests
|
+-- LoginTest.java
+-- RegistrationTest.java
+-- SearchTest.java
+-- CartTest.java
+-- CheckoutTest.java
+-- LogoutTest.java
This structure makes test classes easier to understand and maintain.
35. Test Method and Page Object Model
In a Page Object Model framework, test methods should generally focus on test scenarios rather than directly containing large amounts of locator and page implementation logic.
Test Method
|
v
LoginPage
|
+-- enterUsername()
+-- enterPassword()
+-- clickLogin()
|
v
HomePage
|
+-- verifyDashboard()
|
v
Assertion
Example
@Test
public void verifyValidLogin() {
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("admin");
loginPage.enterPassword("admin123");
loginPage.clickLogin();
Assert.assertTrue(
driver.getCurrentUrl().contains("dashboard")
);
}
36. Test Method vs Configuration Method
| Feature | Test Method | Configuration Method |
| Typical Annotation | @Test | @BeforeMethod, @AfterMethod, etc. |
| Purpose | Executes the actual test scenario | Prepares or cleans up test execution |
| Contains Business Validation | Usually yes | Usually no |
| Example | Verify login | Start browser |
| Execution | Test execution stage | Configuration stage |
37. Test Method vs Normal Java Method
| Normal Java Method | TestNG Test Method |
| Uses normal Java method syntax | Uses normal Java syntax plus @Test |
| Not automatically executed by TestNG as a test | Recognized by TestNG as a test method |
| No TestNG test metadata | Can use TestNG attributes |
| Usually called by application code | Scheduled and executed by TestNG |
38. Test Methods and Test Execution Results
TestNG generally reports test methods according to their execution result.
Test Method
|
+-- Executes Successfully
| |
| +-- PASS
|
+-- Assertion / Execution Failure
| |
| +-- FAIL
|
+-- Dependency / Configuration Condition
|
+-- SKIP
| Result | Meaning |
| PASS | Test completed successfully according to its validations |
| FAIL | Test encountered an assertion or execution failure |
| SKIP | Test was not executed, commonly due to dependency or configuration behavior |
39. Test Methods with Failure Screenshots
A common Selenium framework pattern is to capture screenshots when a test fails. This can be implemented through listeners, configuration methods, or framework utilities.
@AfterMethod(alwaysRun = true)
public void tearDown() {
// Capture screenshot if test failed
if (driver != null) {
driver.quit();
}
}
In larger frameworks, a TestNG listener is often used to automatically detect failures and capture screenshots.
40. Test Methods with testng.xml
Test methods can be selected and organized using TestNG's XML configuration.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Automation Suite">
<test name="Login Tests">
<classes>
<class name="LoginTest"/>
</classes>
</test>
</suite>
The XML file defines which classes or groups participate in a suite, while the test methods inside those classes define the actual test scenarios.
41. Selecting Test Methods Using Groups
Groups allow teams to execute selected categories of test methods.
<suite name="Smoke Suite">
<test name="Smoke Tests">
<groups>
<run>
<include name="smoke"/>
</run>
</groups>
<classes>
<class name="LoginTest"/>
<class name="SearchTest"/>
</classes>
</test>
</suite>
This allows a suite to focus on test methods assigned to the selected group.
42. Practical Login Test Methods
BaseTest.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com/login");
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
LoginTest.java
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test(description = "Verify login with valid credentials")
public void validLoginTest() {
driver.findElement(By.id("username"))
.sendKeys("admin");
driver.findElement(By.id("password"))
.sendKeys("admin123");
driver.findElement(By.id("login"))
.click();
Assert.assertTrue(
driver.getCurrentUrl().contains("dashboard")
);
}
@Test(description = "Verify login validation with invalid credentials")
public void invalidLoginTest() {
driver.findElement(By.id("username"))
.sendKeys("wrong");
driver.findElement(By.id("password"))
.sendKeys("wrong123");
driver.findElement(By.id("login"))
.click();
Assert.assertTrue(
driver.getPageSource().contains("Invalid")
);
}
}
43. Practical E-Commerce Test Methods
public class EcommerceTest extends BaseTest {
@Test(groups = "smoke")
public void verifyProductSearch() {
System.out.println("Search product");
}
@Test(groups = "regression")
public void verifyAddToCart() {
System.out.println("Add product to cart");
}
@Test(groups = "regression")
public void verifyCheckout() {
System.out.println("Checkout");
}
@Test(groups = "regression")
public void verifyLogout() {
System.out.println("Logout");
}
}
44. Common Mistakes in Test Methods
Mistake 1: Forgetting @Test
public void loginTest() {
System.out.println("Login");
}
This method is not identified as a normal TestNG test method.
Correct
@Test
public void loginTest() {
System.out.println("Login");
}
Mistake 2: Putting All Tests into One Large Method
@Test
public void completeApplicationTest() {
// Login
// Search
// Add product
// Checkout
// Logout
}
Large methods are difficult to debug and maintain. Where appropriate, independent scenarios should be separated into meaningful test methods.
Mistake 3: Using Test Methods for Browser Setup
Browser setup should generally be placed in configuration methods rather than duplicated inside every test method.
Mistake 4: Sharing State Between Tests
One test should not unnecessarily depend on data or browser state created by another test.
Mistake 5: Excessive Test Dependencies
Too many dependencies can cause a single failure to skip many unrelated tests.
Mistake 6: Using Priority as a Dependency Mechanism
Priority controls relative ordering; it does not express a business dependency. Use dependsOnMethods when a genuine dependency exists.
Mistake 7: Not Cleaning Up WebDriver
Browser sessions should be closed reliably using appropriate configuration methods.
45. Best Practices for Test Methods
- Keep each test method focused on one logical scenario.
- Use descriptive test method names.
- Use meaningful descriptions where helpful.
- Keep test methods reasonably short and readable.
- Separate setup and cleanup from test logic.
- Use Page Object Model for maintainable Selenium code.
- Use assertions to validate expected behavior.
- Use DataProvider for multiple test data sets.
- Use groups for execution categorization.
- Use dependencies only when genuinely required.
- Avoid unnecessary priority-based test design.
- Keep tests independent wherever practical.
- Use appropriate waits for Selenium synchronization.
- Ensure browser cleanup happens even after failures.
- Design test data and WebDriver instances carefully for parallel execution.
- Keep reusable business actions outside the test method when appropriate.
46. Recommended Test Method Structure
@Test
public void verifyLogin() {
// Arrange
String username = "admin";
String password = "admin123";
// Act
loginPage.enterUsername(username);
loginPage.enterPassword(password);
loginPage.clickLogin();
// Assert
Assert.assertTrue(
homePage.isDashboardDisplayed()
);
}
This structure follows the common Arrange → Act → Assert pattern and keeps the test scenario easy to understand.
47. Test Method and Automation Framework Architecture
Selenium Framework
|
+----------+----------+
| |
TestNG Selenium
| |
v v
Test Methods WebDriver
|
+-------+--------+
| | |
v v v
Login Search Checkout
|
v
Page Objects
|
v
Assertions
|
v
Test Result
|
v
Reporting
|
v
CI/CD
48. Test Methods and Parallel Execution
TestNG can execute tests in parallel according to the configured suite and execution strategy. Parallel execution can reduce overall execution time, but test methods must be designed carefully.
Parallel Execution
|
+----------------+
| |
v v
Test Method A Test Method B
| |
v v
WebDriver A WebDriver B
| |
v v
Browser A Browser B
Sharing a single WebDriver instance across parallel tests without appropriate synchronization can cause test interference. A framework should provide isolated browser sessions or another thread-safe design.
49. Test Method Execution with DataProvider
DataProvider
|
+-- Data Set 1
|
+-- Data Set 2
|
+-- Data Set 3
|
v
@Test Method
|
+-- Execute with Data Set 1
|
+-- Execute with Data Set 2
|
+-- Execute with Data Set 3
|
v
Test Results
This approach avoids creating separate test methods for every data combination.
50. Test Method Design Example
public class LoginTest extends BaseTest {
@Test(groups = "smoke")
public void verifyLoginPageIsDisplayed() {
// Verify login page
}
@Test(groups = "smoke")
public void verifyValidLogin() {
// Verify valid login
}
@Test(groups = "regression")
public void verifyInvalidLogin() {
// Verify invalid credentials
}
@Test(groups = "regression")
public void verifyForgotPassword() {
// Verify forgot password
}
}
This organization makes it easier to execute smoke tests separately from regression tests.
51. Advantages of Well-Designed Test Methods
- Easy to understand.
- Easy to maintain.
- Easy to debug.
- Easy to execute independently.
- Easy to categorize using groups.
- Easy to parameterize using DataProvider.
- Easy to integrate with reporting.
- Easy to execute through CI/CD.
- Supports reusable framework design.
- Improves automation code readability.
52. Test Methods in a Real Selenium Framework
Automation Project
|
+-- src/main/java
| |
| +-- pages
| +-- utilities
| +-- base
|
+-- src/test/java
| |
| +-- LoginTest.java
| +-- SearchTest.java
| +-- CartTest.java
| +-- CheckoutTest.java
|
+-- testng.xml
|
+-- pom.xml
|
+-- reports
|
+-- screenshots
Test classes contain test methods, page classes contain page-level interactions, utilities contain reusable functionality, and TestNG controls test execution.
53. Test Method Execution Flow in a Real Project
testng.xml
|
v
TestNG
|
v
Identify Test Classes
|
v
Identify @Test Methods
|
v
@BeforeMethod
|
v
Test Method
|
+-- Selenium Actions
+-- Page Objects
+-- Assertions
|
v
@AfterMethod
|
v
Test Result
|
+-- Pass
+-- Fail
+-- Skip
|
v
Report
54. Interview Questions on Test Methods
Q1. What is a TestNG test method?
A TestNG test method is a Java method annotated with @Test that TestNG recognizes and executes as a test.
Q2. What is the purpose of @Test?
The @Test annotation identifies a method as a TestNG test method.
Q3. Can one TestNG class contain multiple test methods?
Yes. A TestNG class can contain multiple methods annotated with @Test.
Q4. What is the difference between a test method and a configuration method?
A test method performs the actual test scenario, while configuration methods such as @BeforeMethod and @AfterMethod prepare or clean up the test execution.
Q5. How can you control the execution priority of test methods?
The priority attribute of @Test can be used to define relative execution order.
Q6. How can you skip a test method?
Use @Test(enabled = false) to disable the test method.
Q7. How can you group test methods?
Use the groups attribute of @Test.
Q8. How can one test method depend on another?
Use dependsOnMethods.
Q9. How can a test depend on a group?
Use dependsOnGroups.
Q10. How can you execute one test method with multiple data sets?
Use @DataProvider together with the dataProvider attribute of @Test.
Q11. What is invocationCount?
invocationCount specifies how many times TestNG should invoke a test method.
Q12. What is expectedExceptions?
It specifies exception types that the test is expected to throw.
Q13. What is the purpose of timeOut?
It defines the maximum allowed execution time for a test method.
Q14. Should test methods depend on one another?
They should generally remain independent unless a genuine business or technical dependency exists.
Q15. Why is Page Object Model useful with test methods?
POM keeps page-specific locators and actions separate from test scenarios, making test methods more readable and maintainable.
55. Quick Revision
| Concept | Remember |
| @Test | Defines a TestNG test method |
| priority | Controls relative execution order |
| enabled | Enables or disables a test |
| groups | Categorizes test methods |
| dependsOnMethods | Creates method dependency |
| dependsOnGroups | Creates group dependency |
| dataProvider | Provides multiple test data sets |
| expectedExceptions | Defines expected exception behavior |
| timeOut | Limits test execution time |
| invocationCount | Runs a test repeatedly |
| description | Describes the test |
| @BeforeMethod | Runs setup before each applicable test |
| @AfterMethod | Runs cleanup after each applicable test |
56. Learning Roadmap
Core Java
|
v
Selenium WebDriver
|
v
Locators
|
v
WebElements
|
v
Browser Interactions
|
v
Waits & Synchronization
|
v
TestNG
|
+-- Test Methods
+-- Test Annotations
+-- Assertions
+-- Test Groups
+-- Test Dependencies
+-- DataProvider
+-- Test Execution
|
v
Page Object Model
|
v
Automation Framework
|
v
Maven
|
v
Git & GitHub
|
v
Reporting
|
v
Jenkins / CI/CD
|
v
Parallel Execution
|
v
Real-Time Selenium Project
57. Summary
Test methods are the core execution units of a TestNG automation suite. A method marked with @Test becomes a TestNG test method and can contain Selenium actions, business validations, and assertions.
TestNG provides several attributes for controlling test methods, including priority, groups, enabled, description, dependsOnMethods, dependsOnGroups, dataProvider, expectedExceptions, timeOut, invocationCount, invocationTimeOut, threadPoolSize, and alwaysRun.
In Selenium automation, well-designed test methods should be focused, readable, independent where practical, and separated from browser setup and cleanup. Combining TestNG test methods with Page Object Model, DataProvider, assertions, reporting, and proper WebDriver management helps create maintainable automation frameworks.
58. Course Resources
Learn more about Selenium WebDriver, TestNG, test methods, test annotations, data-driven testing, automation frameworks, and real-world Selenium projects through the following resources:
Selenium Training
Register for Course Demo